package com.gonsin.gview.example.gview.user;

import com.gonsin.gview.annotations.GView;
import com.gonsin.gview.annotations.actions.GAction;
import com.gonsin.gview.annotations.board.GBoard;
import com.gonsin.gview.annotations.board.GButton;
import com.gonsin.gview.annotations.board.form.*;
import com.gonsin.gview.annotations.data.GData;
import com.gonsin.gview.annotations.data.GListData;
import com.gonsin.gview.annotations.data.GParam;
import com.gonsin.gview.annotations.enums.InputType;
import com.gonsin.gview.example.bean.UserBean;
import com.gonsin.gview.example.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;

import static com.gonsin.gview.annotations.enums.ButtonAction.CONFIRM_AND_CLOSE;


@GView(
        viewName = "UpdateUserPassword",
        title = "修改密码",
        props = {"userId"},
        boards = {
                @GBoard(form = @GForm(
                        data = @GData(fromSql = "select * from gs_user where id = ${userId}"),
                        formItems = {
                                @GFormItem(selector = @GSelector(name = "选择权限组", keyName = "groupId", listData = @GListData(
                                        fromSql = "select id as groupId, name from gs_user_group",
                                        keyName = "name",
                                        valueName = "groupId"
                                ))),
                                @GFormItem(hidden = @GHidden(keyName = "userId", valueName = "keyOnly")),
                                @GFormItem(label = @GLabel(name = "人员名字：", keyName = "realName")),
                                @GFormItem(textInput = @GTextInput(name = "密   码：", keyName = "password", inputType = InputType.PASSWORD, showIf = "console.log('123123')")),
                                @GFormItem(textInput = @GTextInput(name = "确认密码：", inputType = InputType.RE_PASSWORD)),
                        },
                        okButton = @GButton(action = CONFIRM_AND_CLOSE, actionName = "updateUserPassword", name = "确定")
                ))
        }
)
@Component
public class UpdateUserPasswordView {

    @Autowired private UserDao userDao;

    /**
     * 修改用户密码
     */
    @Transactional
    @GAction("updateUserPassword")
    public void updateUserPassword(HttpSession session, @GParam("userId") int userId, @GParam("password") String newPassword){
        UserBean user = userDao.findById(userId).orElse(null);
        user.setPassword(newPassword);
        userDao.saveAndFlush(user);
    }

}
